
const path = require('path')
/**
 *
 * @param Table
 * @returns Model
 * @constructor
 */
function M(Table){
    return new Model(Table,Config.DATABASE.DB_PREFIX);
}

/**
 * 仿造php的array_columns函数
 * @param arr
 * @param column
 * @returns {Array}
 */
function array_columns(arr:any,column:any,unique=false){
    let a=[];
    _.forOwn(arr,(v:any,k)=>{
        if(unique){
            if(a.indexOf(v[column])==-1){
                a.push(v[column])
            }
        }else{
            a.push(v[column])
        }
    })
    return a;
}

/**
 * 取唯一值
 * @param arr
 */
function array_unique(arr){
    return _.unique(arr)
}
/**
 *
 * @param name
 * @param {boolean} force
 * @returns Relation
 * @constructor
 */
function R(name,force=false){
    const Relations={};
    if(!_.isObject(Relations[name])){
        try{
            var r = require(Config.APP_PATH+'/app/Relation.js');
            if(r&&r[name]){
                Relations[name]=r[name];
            }else{
                Relations[name]=new Relation(name,Config.getTableFields(name),Config.getTablePK(name));
            }
        }catch (e){
            Relations[name]=new Relation(name,Config.getTableFields(name),Config.getTablePK(name));
        }
    }
    return Relations[name];
}
exports.array_columns=array_columns;
exports.array_unique=array_unique;
/**
 * 密码加密
 * @param pwd
 * @returns {string}
 */
function password_hash (pwd):string {
    const md5 = crypto.createHash('md5');
    return md5.update(pwd).digest('hex').toLowerCase();
}
exports.password_hash=password_hash;
/**
 * 密码验证
 * @param pwd
 * @param sign
 * @returns {boolean}
 */
function password_verify (pwd,sign):boolean {
    const md5 = crypto.createHash('md5');
    return md5.update(pwd).digest('hex').toLowerCase()==sign;
}
exports.password_verify=password_verify;
exports.M=M;
exports.R=R;

/**
 * 移动上传文件到指定地址
 * @param file
 * @param to
 */
var move_upload_file = module.exports.move_upload_file = function (file,to){
    fs.renameSync(file.path,to)
}

/**
 * 接受用户上传的所有文件，
 * @param req
 * @returns {any[]}
 */
var accept_upload_file = module.exports.accept_upload_file = function (req){
    var files=[];
    _.forOwn(req.files,(file)=>{
        let d = file.path.substr(0,file.path.length-4);
        files.push(d);
        move_upload_file(file,d);
    })
    return files;
}

// 创建所有目录
var mkdirs = module.exports.mkdirs = function(dirpath, mode=0o777, callback=null) {
    if(fs.existsSync(dirpath)){
        return true;
    }else{
        let parent_path = path.dirname(dirpath);
        if(fs.existsSync(parent_path)){
            return fs.mkdirSync(dirpath)
        }else{
            return mkdirs(parent_path)
        }
    }
};